<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Cache;
use App\Http\Requests\User\StoreUserResource;
use App\Http\Requests\User\UpdateUserResource;
use App\Http\Requests\User\DestroyUserResource;
use App\Http\Requests\User\QueryUserCollection;

/**
 * 用户管理控制器
 *
 * Date: 2018/2/2
 * @author George
 * @package App\Http\Controllers
 */
class UserController extends Controller
{
	/**
	 * 获取用户数据
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param QueryUserCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(QueryUserCollection $request)
    {
    	$params = $this->validate($request, [
    		'name' => 'nullable',
    		'staffid' => 'nullable',
		]);

    	$admin = $request->get('admin');

    	$paginate = $request->get('paginate', 10);

    	$query = User::query();

    	foreach ($params as $key => $value) {
    		if ($value) {
    			$query->where($key, 'like', '%'.$value.'%');
			}
		}

		if ($admin) {
    		$query->where('admin', 1);
		}

		return $this->success($query->paginate($paginate));
    }

	/**
	 * 根据ID 获取用户信息
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param Request $request
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Request $request, User $user)
    {
        $menu = $request->get('menu');
        $role = $request->get('role');
        $permission = $request->get('permission');

        if ($role) {
            return $this->success(array_pluck($user->roles, 'code'));
        }

        if ($permission) {
			return $this->success(array_pluck($user->permissions, 'code'));
        }

        if ($menu) {
            $user->menus;
        }

        return $this->success($user);
    }

	/**
	 * 创建用户信息
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param StoreUserResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
    public function store(StoreUserResource $request)
    {
    	$attributes = $this->validate($request, [
    		'name' => 'required',
    		'staffid' => 'required|unique:users',
    		'gender' => 'nullable',
    		'email' => 'nullable',
    		'password' => 'required|alpha_dash|between:6,15',
    		'avatar' => 'nullable',
    		'admin' => 'nullable',
            'remarks' => 'nullable',
            'phone' => 'nullable',
		], [
			'name.required' => '用户姓名不能为空',
			'staffid.required' => '用户工号不能为空',
			'staffid.unique' => '您输入的工号已存在',
			'password.required' => '密码不能为空',
			'password.alpha_dash' => '密码只能是字幕和数字',
			'password.between' => '密码长度必须在6到15个字符之间',
		]);

    	$user = new User();

    	foreach ($attributes as $key => $value) {
    		$user->{$key} = $value;
		}

		$user->saveOrFail();

		if ($attributes['admin']) {
			$roles = $request->get('roles');
			$user->roles()->sync($roles);
		}

    	return $this->stored($user);
    }

	/**
	 * 更新用户信息
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param UpdateUserResource $request
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function update(UpdateUserResource $request, User $user)
    {
		$attributes = $this->validate($request, [
			'name' => 'required',
			'staffid' => [
				'required',
				//如果工号未发生改变则忽略
				Rule::unique('users')->ignore($user->id),
			],
			'gender' => 'nullable',
			'email' => 'nullable',
			'avatar' => 'nullable',
			'admin' => 'nullable',
            'remarks' => 'nullable',
            'phone' => 'nullable',
		], [
			'name.required' => '用户姓名不能为空',
			'staffid.required' => '用户工号不能为空',
			'staffid.unique' => '您输入的工号已存在',
		]);

		$result = $user->update($attributes);

		if ($result) {
			if ($attributes['admin']) {
				$roles = $request->get('roles');
				$user->roles()->sync($roles);
			}

			Cache::forget("users:{$user->id}");
			Cache::forget("users:{$user->id}:permissions");
			Cache::forget("users:{$user->id}:roles");

			return $this->updated($user);
		}

		return $this->failed('修改用户信息失败');
    }

	/**
	 * 删除用户信息
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param DestroyUserResource $request
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
    public function destroy(DestroyUserResource $request, User $user)
    {
    	$result = $user->delete();

    	if ($result) {
    		return $this->deleted();
		}

		return $this->failed('删除用户信息失败');
    }

	/**
	 * 获取用户信息用于关联其他模型
	 *
	 * Date: 2018/2/3
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function getAllUsers(Request $request)
	{
//	    $shop = new Shop();

//        $shop_user = $shop->with('users')->get();

//        return $this->success($shop_user);
		$users = User::query()->select(['id', 'name', 'staffid'])->get();
		return $this->success($users);
    }

}
